package 练习;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author caihe
 * @date 2022/11/14 14:46
 */
public class ReadWriteLockTest {


    public static void main(String[] args) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        Lock read = lock.readLock();
        Lock write = lock.writeLock();


        new Thread(() -> {
            write.lock(); // 加写锁  写锁 下 再加 读锁
            try {
                System.out.println("寫。。。。");
                read.lock(); // 加读锁 锁降级？？
                try {
                    System.out.println("讀。。。。");
                } finally {
                    write.unlock(); // 释放写锁

                }
            } finally {
                read.unlock();
            }
        }, "写线程").start();

        new Thread(() -> {
            read.lock(); // 加读锁
            try {
                System.out.println("讀。。。。");
            } finally {
                read.unlock(); // 释放读锁
            }
        }, "读线程1").start();
        new Thread(() -> {
            read.lock(); // 加读锁
            try {
                System.out.println("讀。。。。");
            } finally {
                read.unlock(); // 释放读锁
            }
        }, "读线程2").start();


        System.out.println();
    }
}
